package config;

import java.beans.PropertyVetoException;
import java.sql.SQLException;


import javax.sql.DataSource;
import javax.transaction.TransactionManager;

import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 和连接数据库相关的配置类
 */
//@PropertySource("/WEB-INF/classes/c3p0.properties")
public class JdbcConfig {
	@Value("${jdbc.driverClass}")
	private String driverClass;

	@Value("${jdbc.jdbcUrl}")
	private String jdbcUrl;

	@Value("${jdbc.user}")
	private String user;

	@Value("${jdbc.password}")
	private String password;

	@Bean(name = "queryRunner")
	public QueryRunner createQueryRunner(ComboPooledDataSource dataSource) throws SQLException {
		QueryRunner queryRunner =new QueryRunner(dataSource);
		queryRunner.getDataSource().getConnection().setAutoCommit(false);
		return queryRunner;
	}

	/**
	 * 创建数据源对象
	 * 
	 * @return
	 * @throws PropertyVetoException
	 */
	@Bean(name = "dataSource")
	public ComboPooledDataSource createDataSource() throws PropertyVetoException, SQLException {
		ComboPooledDataSource ds = new ComboPooledDataSource();
		ds.setDriverClass(driverClass);
		ds.setJdbcUrl(jdbcUrl);
		ds.setUser(user);
		ds.setPassword(password);
		ds.setAutoCommitOnClose(false);
		ds.getConnection().setAutoCommit(false);
		return ds;
	}
//
//	@Bean("transactionManager")
//	public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
//		return new DataSourceTransactionManager(dataSource);
//	}
//
//	@Bean("transactionTemplate")
//	public TransactionTemplate getTransactionTemplate(DataSourceTransactionManager transactionManager){
//		TransactionTemplate transactionTemplate = new TransactionTemplate();
//		transactionTemplate.setTransactionManager(transactionManager);
//		return transactionTemplate;
//	}
}
